package com.duda.controller;

import com.alibaba.fastjson.JSON;
import com.duda.projo.DownFileUser;
import com.duda.projo.ResultEntity;
import com.duda.service.DownFileUserService;
import com.duda.util.GetDownloadUrlForNT;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;


@Controller
@ResponseBody
@CrossOrigin
public class IndexController {

    @Resource
    DownFileUserService downFileUserService;

    // 上次登录时间
    long oldLoginDate= 0;

    @GetMapping("/XIAZAI")
    public String getNipicUrl(String Url, String UserID) {
        ResultEntity resultEntity = new ResultEntity();
        resultEntity.setCode("0");
        try {
            int type = GetSourceType(Url);
            String sqlStr = "select * from APP_DownFileUser where ID='" + UserID + "'";
            List<DownFileUser> downFileUsers = downFileUserService.getDownFileUser(UserID);
            if (downFileUsers != null && downFileUsers.size() > 0) {
                // 积分
                int integral = downFileUsers.get(0).getIntegral();
                if (integral > 100) {
//                    List<DownFileHistory> downFileHistories = downFileHistoryService.getDownFileHistory(url);
//                    if (downFileHistories != null && downFileHistories.size() > 0) {
//                        if (downFileHistories != null && downFileHistories.size() > 0) {
//                            Map<String, String> map = new HashMap<>();
//                            map.put("FileUrl", downFileHistories.get(0).getLocalUrl());
//                            resultEntity.setCode("1");
//                            resultEntity.setResultObject(map);
//                        } else {
//                            resultEntity.setCode("0");
//                            resultEntity.setMsg("系统正在维护中......");
//                        }
//                    } else {
//                        // 判断资源是否可以下载
//                        int sourceTrue = 0;
//                        switch (type) {
//                            case 0:
//                                sourceTrue = 1;
//                                break;
//                            default:
//                                break;
//                        }
//                        if (sourceTrue == 0) {
//                            resultEntity.setCode("0");
//                            resultEntity.setMsg("下载链接格式不正确！");
//                        } else {
//                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss\"");
//                            sqlStr = "insert into APP_DownFileHistory values('" + UUID.randomUUID() + "','"
//                                    + url + "','','" + type + "','" + userID + "','"
//                                    + 0 + "','0','" + sourceTrue + "','" + format.format(new Date()) + "')";
//                            SqlSessionFactory factory = FKSqlSessionFactory.getSqlSessionFactory();
//                            SqlSession session = factory.openSession();
//                            DownFileHistoryMapper downFileHistoryMapper = session.getMapper(DownFileHistoryMapper.class);//获取映射器实例
//                            String msg = "";
//                            int downCount = 0;
//                            while (downCount++ < 6) {
//                                List<DownFileHistory> downFileHistoryList=downFileHistoryMapper.getDownFileHistory(url,1,1);
//                                if (downFileHistoryList != null && downFileHistoryList.size() > 0) {
//                                    Map<String,String> keyValuePairs=new HashMap<>();
//                                    keyValuePairs.put("FileUrl", downFileHistoryList.get(0).getLocalUrl());
//                                    resultEntity.setCode("1");
//                                    resultEntity.setResultObject(keyValuePairs);
//                                    break;
//                                }
//                                Thread.sleep(5000);
//                            }
//                        }
//                    }
                    //判断资源是否可以下载
                    int sourceTrue = 0;
                    switch (type) {
                        case 0:
                            sourceTrue = 1;
                            break;
                        default:
                            break;
                    }
                    if (sourceTrue == 0) {
                        resultEntity.setCode("0");
                        resultEntity.setMsg("下载链接格式不正确！");
                    }
                    else {
                        String webUrl = GetDownloadUrlForNT.getDownloadUrl(Url);
                        if ("000000".equals(webUrl))
                        {
                            resultEntity.setCode("0");
                            resultEntity.setMsg(webUrl);
                        }
                        else {
                            resultEntity.setCode("1");
                            resultEntity.setMsg(webUrl);
                            DeductIntegral(UserID);
                        }
                    }
                }
                else
                {
                    resultEntity.setCode("0");
                    resultEntity.setMsg("积分不足，请联系管理员！");
                }
            }
        } catch (Exception exception) {
            resultEntity.setCode("0");
            resultEntity.setMsg("系统错误：" + exception.getMessage());
        }
        String json = JSON.toJSONString(resultEntity);
        return json;
    }

    private void DeductIntegral(String userID)
    {
        downFileUserService.deductUserIntegral(userID);
    }

    @GetMapping("/Login")
    public String Login(String UserName,String PassWord)
    {
        ResultEntity resultEntity = new ResultEntity();
        resultEntity.setCode("0");
        try
        {
            if (UserName!= null && PassWord != null)
            {
                List<DownFileUser> downFileUsers = downFileUserService.getDownFileUser(UserName,PassWord);
                if (downFileUsers != null && downFileUsers.size() > 0)
                {
                    long nowDate = new Date().getTime();
                    int m = (int)(nowDate - oldLoginDate)/(1000*60);
                    if(m>30) {
                        try {
                            GetDownloadUrlForNT.LoginNT();
                        }catch (Exception e) {
                            e.printStackTrace();
                        }
                        oldLoginDate= nowDate;
                    }
                    resultEntity.setCode("1");
                    resultEntity.setMsg(downFileUsers.get(0).getId());
                }
                else
                {
                    resultEntity.setCode("0");
                    resultEntity.setMsg("用户名或密码错误！");
                }
            }
            else
            {
                resultEntity.setCode("0");
                resultEntity.setMsg("参数错误！");
            }
        }
        catch (Exception ex)
        {
            resultEntity.setCode("0");
            resultEntity.setMsg("系统错误："+ex.getMessage());
        }
        String json = JSON.toJSONString(resultEntity);
        return json;
    }

    private int GetSourceType(String url) {
        //http://www.nipic.com/show/28481910.html
        // 0：昵图网 1：其他
        int type = -1;
        String content = url;
        String pattern = "http://down\\.nipic\\.com/download\\?id=[0-9]{5,10}(#showMore){0,1}";
        boolean isMatch = Pattern.matches(pattern, content);
        if (isMatch) {
            type = 0;
        }
        return type;
    }

    public final static String[] LOWER_CASES = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
    public final static String[] UPPER_CASES = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
//    public final static String[] UPPER_CASES = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
    public final static String[] NUMS_LIST = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
    public final static String[] SYMBOLS_ARRAY = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};

    @GetMapping("/InsertUser")
    public String InsertUser(int Integral)
    {
        String userName= genRandomPwd(8);
        String passWord = genRandomPwd(6);
        UUID id=UUID.randomUUID();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss\"");
        downFileUserService.insertUser(id,userName,passWord,Integral,format.format(new Date()));
        return "温馨提示：\r\n（1）通过\r\nhttp://www.shaoyasoft.com 下载素材。请使用电脑下载！打开我发给你的网址登录" +
                " 复制你要下载的素材链接进去下载即可。\r\n用户名："+userName + "\r\n密码:"+passWord;
    }

    /**
     * 生成随机密码
     * @param pwd_len 密码长度
     * @return 密码的字符串
     */
    public String genRandomPwd(int pwd_len) {
        if ( pwd_len < 6 || pwd_len >20 ) {
            return "";
        }
        int lower = pwd_len / 2 ;

        int upper = (pwd_len - lower) /2;

        int num =  (pwd_len - lower) / 2;

        int symbol = pwd_len - lower - upper - num ;

        StringBuffer pwd = new StringBuffer();
        Random random = new Random();
        int position = 0;
        while((lower + upper + num + symbol) > 0 ){
            if(lower > 0){
                position = random.nextInt(pwd.length() + 1);

                pwd.insert(position,LOWER_CASES[random.nextInt(LOWER_CASES.length)]);
                lower--;
            }
            if(upper > 0){
                position = random.nextInt(pwd.length()  + 1);

                pwd.insert(position,UPPER_CASES[random.nextInt(UPPER_CASES.length)]);
                upper--;
            }
            if(num > 0){
                position = random.nextInt(pwd.length()  + 1);

                pwd.insert(position,NUMS_LIST[random.nextInt(NUMS_LIST.length)]);
                num--;
            }
            if(symbol > 0){
                position = random.nextInt(pwd.length()  + 1);

                pwd.insert(position,SYMBOLS_ARRAY[random.nextInt(SYMBOLS_ARRAY.length)]);
                symbol--;
            }

            System.out.println(pwd.toString());
        }


        return pwd.toString();
    }
}
